package com.monika.main.system.exception.config;

import com.monika.main.system.domain.AjaxResult;
import com.monika.main.system.exception.BlackListException;
import com.monika.main.system.exception.UserPasswordRetryExceedException;
import com.monika.main.system.factory.LogManager;
import com.monika.main.system.util.StringUtil;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @Author whh
 * @Date: 2023/04/15/ 1:31
 * @description
 */
@RestControllerAdvice
public class GlobalExceptionHandler {



    @ExceptionHandler(value = AuthenticationException.class)
    @ResponseBody
    public String authenticationExceptionHandle(AuthenticationException e) {
        String message;
        if (e instanceof LockedException) {
            message = "账户锁定";
        } else if (e instanceof DisabledException) {
            message = "账户不可用";
        } else if (e instanceof AccountExpiredException) {
            message = "账户过期";
        } else if (e instanceof UserPasswordRetryExceedException) {
            UserPasswordRetryExceedException ex = (UserPasswordRetryExceedException) e;
            message = ex.getMessage() + ",please wait "+ex.getLockTime()+" minutes";
        } else if(e instanceof BadCredentialsException) {
            message = "账户凭证错误";
        }else{
            message = "认证失败";
        }
        LogManager.LOG().sys_global_exception_log(null).error(message, e);
        return AjaxResult.fail(message).ajaxResultJson();
    }

    /**
     * ip黑名单异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = BlackListException.class)
    @ResponseBody
    public String blackIpExceptionHandler(BlackListException e) {
        LogManager.LOG().sys_global_exception_log(null).error(e.getMessage(), e);
        return AjaxResult.exception(StringUtil.substring(e.getMessage(), 0, 2000)).ajaxResultJson();
    }


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String exceptionHandler(Exception e) {
        LogManager.LOG().sys_global_exception_log(null).error(e.getMessage(), e);
        return AjaxResult.exception(StringUtil.substring(e.getMessage(), 0, 2000)).ajaxResultJson();
    }


}
